# aiohttp、aiofiles
import asyncio
import aiohttp
import aiofiles

async def download(params):
    print('开始下载！',params)
    file_name = params.split('/')[-1]
    # aiohttp.ClientSession() 等同于 requests
    async with aiohttp.ClientSession() as session:
        # 发送网络请求
        async with session.get(params) as resp:
            # await resp.text()  # 等同于 resp.text 这里变成了函数
            content = await resp.content.read()  # 等同于 resp.content
            # 写入文件
            async with aiofiles.open(r'D:\ui\reptile_next\sync_img\\'+file_name,'wb') as f:
                await f.write(content)
    print('下载完成！',params)

async def main():
    params_list = [
        "https://www.umei.cc/d/file/20230914/f16eacf43b6476fa4eb24d8f22e0c22f.jpg",
        "https://www.umei.cc/d/file/20230428/12e25f71c766fd6ce33c6e879495971d.jpg",
        "https://www.umei.cc/d/file/20230215/f751c8572ccbd8cb5c7a190394f6c4b5.jpg",
        "https://www.umei.cc/d/file/20230628/fd13d5c4ffd645f6c99773b2777e8735.jpg",
        "https://www.umei.cc/d/file/20230628/5419a9b2012f7558d1896f64b40b91ac.jpg"
    ]
    tasks = []
    for params in params_list:
        task = asyncio.create_task(download(params))
        tasks.append(task)
    await asyncio.wait(tasks)

if __name__ == '__main__':
    event_loop = asyncio.get_event_loop()  # 拿到事件循环
    event_loop.run_until_complete(main())  # event_loop 执行协程对象，直到该对象内的内容执行完毕为止
    # asyncio.run(main())

